<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>AngulaJS 服务</title>
		<style>
			body{
			  font-family: 'microsoft yahei',Arial,sans-serif;
			}
			
			h1{
			  font-weight:500;
			  font-size:24px;
			}
			
			input,button{
			  padding:10px;
			}

		</style>
	</head>

	<body>
		<h1>AngularJS依赖注入演示</h1>
	<hr>
	<div ng-app="mainApp" ng-controller="MY_Ctl">
		<p>输入一个数值：</p>	
		<p><input type="number" ng-model="number" /></p>
		<button ng-click="square()">计算平方 X<sup>2</sup></button>
		<p>{{result}}</p>
	</div>
		
		<script src="http://cdn.gbtags.com/angular.js/1.2.20/angular.min.js"></script>
		<script>
			var mainApp = angular.module("mainApp", []);
			
			// 配置
			/*
			 Provider主要用来在配置阶段创建Service，Factory等等。
			 下面的script可以用来创建MathService。
			 Provider是一个指定的工厂方法，包含一个get方法来返回value/service/factory
			 * */
			mainApp.config(function($provide){
				$provide.provider('MathService', function(){
					this.$get = function(){
						var factory = {};
						factory.multiply = function(a, b){
							return a * b;
						};
						return factory;
					};
				});
			});
			
			// 设置变量默认值
			mainApp.value('defaultInput', 5);
			
			// 工厂，为服务生产对像，等同于上面配置中的服务
//			mainApp.factory('MathService', function(){
//				var factory = {};
//				factory.multiply = function(a, b){
//					return a * b;
//				};
//				return factory;
//			});
			
			mainApp.service('MY_Serv', function(MathService){
				this.square = function(a){
					return MathService.multiply(a, a);
				};
			});
			
			mainApp.controller('MY_Ctl', function($scope, MY_Serv, defaultInput){
				$scope.number = defaultInput;
				$scope.result = MY_Serv.square($scope.number);
				
				$scope.square = function(){
					$scope.result =  MY_Serv.square($scope.number);
				};
			});
			
		</script>
	</body>

</html>